package com.itheima.easy.handler.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePayResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradeConstant;
import com.itheima.easy.enums.TradeEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.FaceToFacePayHandler;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName AliFaceToFacePayHandler.java
 * @Description 支付宝扫码付支付实现
 */
@Slf4j
@Component
public class AliFaceToFacePayHandler extends AliCommonPayHandler implements FaceToFacePayHandler {

    @Override
    public TradeVo payTrade(TradeVo tradeVo) {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            //4、调用支付宝API
            AlipayTradePayResponse payResponse = Factory.Payment
                .FaceToFace().pay(tradeVo.getMemo(),
                    String.valueOf(tradeVo.getTradeOrderNo()),
                    String.valueOf(tradeVo.getTradeAmount()),
                    tradeVo.getAuthCode()
                );
            //5、受理结果【只表示请求是否成功，而不是支付是否成功】
            boolean isSuccess = ResponseChecker.success(payResponse);
            //6、受理成功：修改交易单
            if (isSuccess&&String.valueOf(tradeVo.getTradeOrderNo()).equals(payResponse.getOutTradeNo())){
                tradeVo.setIsRefund(SuperConstant.NO);
                tradeVo.setResultCode(payResponse.getCode());
                tradeVo.setResultMsg(payResponse.getMsg());
                tradeVo.setResultJson(JSONObject.toJSONString(payResponse));
                tradeVo.setTradeState(TradeConstant.TRADE_SUCCESS);
            }else {
                log.error("网关：支付宝商家扫用户统一下单创建：{},结果：{}", tradeVo.getTradeOrderNo(),
                        JSONObject.toJSONString(payResponse));
                throw new RuntimeException("网关：支付宝商家扫用户统一下单创建失败！");
            }
        } catch (Exception e) {
            log.error("支付宝商家扫用户统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradeEnum.PAYING_TRADING_FAIL);
        }
        return tradeVo;
    }

    @Override
    public TradeVo precreateTrade(TradeVo tradeVo)  {
        //1、获得支付宝配置文件
        Config config = aliPayConfig.config();
        //2、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradeEnum.CONFIG_ERROR);
        }
        //3、使用配置
        Factory.setOptions(config);
        try {
            //4、调用支付宝API面对面支付
            AlipayTradePrecreateResponse precreateResponse = Factory.Payment.FaceToFace()
                .preCreate(tradeVo.getMemo(),
                String.valueOf(tradeVo.getTradeOrderNo()),
                String.valueOf(tradeVo.getTradeAmount()));
            //5、受理结果【只表示请求是否成功，而不是支付是否成功】
            boolean isSuccess = ResponseChecker.success(precreateResponse);
            //6、受理成功：修改交易单
            if (isSuccess&&!EmptyUtil.isNullOrEmpty(precreateResponse.getQrCode())){
                tradeVo.setIsRefund(SuperConstant.NO);
                tradeVo.setPlaceOrderCode(precreateResponse.getCode());
                tradeVo.setPlaceOrderMsg(precreateResponse.getMsg());
                tradeVo.setPlaceOrderJson(precreateResponse.getQrCode());
                tradeVo.setTradeState(TradeConstant.TRADE_WAIT_BUYER_PAY);
            }else {
                log.error("网关：支付宝商家扫用户统一下单创建：{},结果：{}", tradeVo.getTradeOrderNo(),
                        JSONObject.toJSONString(precreateResponse));
                throw new RuntimeException("网关：支付宝商家扫用户统一下单创建失败！");
            }
        } catch (Exception e) {
            log.error("支付宝用户扫商家统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(TradeEnum.PAYING_TRADING_FAIL);
        }
        return tradeVo;
    }

}
